package system.config.quartz.scheduler;

import common.model.enums.ApplicationRunnerOrderEnum;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import system.config.quartz.util.JobEnum;
import system.config.quartz.util.TriggerEnum;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 启动所有的定时任务
 *
 * @author mizepeng
 * @since 2022/12/27 上午 10:17
 */
@Slf4j
@Component
public class JobScheduler implements ApplicationRunner, Ordered {

	public static final Map<JobEnum, TriggerEnum> JOBS_AND_TRIGGERS = new HashMap<>(1);

	// 配置所有的定时任务和触发器
	static {
		JOBS_AND_TRIGGERS.put(JobEnum.AvatarDeleteJob, TriggerEnum.AvatarDeleteJobTrigger);
	}

	@Resource
	public Scheduler scheduler;

	@Override
	public void run(ApplicationArguments args) throws Exception {
		scheduleAllJobs();
	}

	/**
	 * 启动所有的定时任务
	 */
	public void scheduleAllJobs() throws SchedulerException {
		for (Map.Entry<JobEnum, TriggerEnum> entry : JOBS_AND_TRIGGERS.entrySet()) {
			JobEnum jobEnum = entry.getKey();
			TriggerEnum triggerEnum = entry.getValue();
			JobDetail jobDetail = JobBuilder.newJob(jobEnum.getClazz()).withIdentity(jobEnum.getName(), jobEnum.getGroup()).build();
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerEnum.getName(), triggerEnum.getGroup()).withSchedule(CronScheduleBuilder.cronSchedule(triggerEnum.getCron())).build();
			scheduler.scheduleJob(jobDetail, trigger);
			log.info("已启动定时任务：{}，触发器：{}，cron：{}", jobEnum.getDescription(), triggerEnum.getDescription(), triggerEnum.getCron());
		}
	}

	@Override
	public int getOrder() {
		return ApplicationRunnerOrderEnum.JOB_SCHEDULER.getOrder();
	}

}
